<template>
  <div class="container message-list">
    <get-user-info v-if="isGetUserInfo" pageType="personal" @showPage="showPage"></get-user-info>
    <!-- 搜索样式展示 -->
    <div v-if="false" class="search-bar flex v-align-c">
      <div class="search flex-item" @click="goSearch">
        <van-icon name="search" color="#aeaeae" size="16px" class="mar-l-8 mar-r-4 flex" />
        <div class="font-14">搜索</div>
      </div>
      <div
        class="change-user font-12 mar-l-12 pad-r-10 pad-l-10"
        @click="statusClick">切换为买家</div>
    </div>
    <div v-if="false" class="height-44"></div>
    <ul class="list">
      <li
      v-for="(item, index) in listData"
      :key="index" @click="$pt.navigateTo({url:'/pages/personal/message/detail/main?memberId=' + item.targetId})">
        <van-swipe-cell :right-width="54" @close="onClose(item,$event)" async-close>
          <div v-if="item.latestMessage" class="flex pad-l-15 pad-r-15 pad-t-10 pad-b-10">
            <template v-if="item.latestMessage.content && item.latestMessage.targetId !== item.latestMessage.senderUserId">
              <img
                v-if="fileSpace && item.latestMessage.content.member"
                :src="item.latestMessage.content.member.avatar ? item.latestMessage.content.member.avatar : fileSpace + '/images/default-avatar.png'"
                class="avatar-img mar-r-10" alt="">
              <div v-if="item.latestMessage.content && item.latestMessage.content.member" class="flex-item">
                <h2 class="font-16 pad-t-2">{{ item.latestMessage.content.member.nickname }}</h2>
                <div class="font-bar-line font-color-9 font-13 pad-t-2 flex v-align-c">
                  <div v-if="item.latestMessage.messageType === 'RC:TxtMsg' && !item.latestMessage.content.order">[内容]</div>
                  <div v-if="item.latestMessage.messageType === 'RC:TxtMsg' && item.latestMessage.content.order">[订单]</div>
                  <div v-if="item.latestMessage.messageType === 'RC:ImgMsg'">[图片]</div>
                  <div v-if="item.latestMessage.messageType === 'RC:TxtMsg'" class="flex-item content-s">{{ item.latestMessage.content.content }}</div>
                </div>
              </div>
            </template>
            <template v-else>
              <img
                v-if="fileSpace && item.latestMessage.content.customer"
                :src="item.latestMessage.content.customer.avatar ? item.latestMessage.content.customer.avatar : fileSpace + '/images/default-avatar.png'"
                class="avatar-img mar-r-10" alt="">
              <div v-if="item.latestMessage.content && item.latestMessage.content.customer" class="flex-item">
                <h2 class="font-16 pad-t-2">{{ item.latestMessage.content.customer.nickname }}</h2>
                <div class="font-bar-line font-color-9 font-13 pad-t-2 flex v-align-c">
                  <div v-if="item.latestMessage.messageType === 'RC:TxtMsg' && !item.latestMessage.content.order">[内容]</div>
                  <div v-if="item.latestMessage.messageType === 'RC:TxtMsg' && item.latestMessage.content.order">[订单]</div>
                  <div v-if="item.latestMessage.messageType === 'RC:ImgMsg'">[图片]</div>
                  <div v-if="item.latestMessage.messageType === 'RC:TxtMsg'" class="flex-item content-s">{{ item.latestMessage.content.content }}</div>
                </div>
              </div>
            </template>
            <div class="list-r">
              <!-- <span class="font-color-9 font-12">{{ item.lastUnreadTime }}</span> -->
              <span class="font-color-9 font-12">{{ item.latestMessage.sentTime }}</span>
              <i v-if="item.unreadMessageCount" class="van-infos mar-t-10">{{ item.unreadMessageCount }}</i>
            </div>
          </div>
          <div slot="right">删除</div>
        </van-swipe-cell>
      </li>
    </ul>
    <div class="pad-t-20" v-if="noneData">
      <img v-if="fileSpace" :src="fileSpace + '/images/shop-nodata.png'" class="width-375 height-91" alt="">
      <div class="align-c mar-t-5 font-16 font-color-6">空空如也</div>
    </div>
  </div>
</template>

<script>
  import GetUserInfo from '@/components/GetUserInfo'
  import { imInit, RongIMLibInit, imGetToken } from '@/api/im'
  import { getMemberInfo } from '@/api/home'
  import { setImToken, setInMessage, setToken } from '@/utils/auth'
  import { getAppInfo } from '@/api/common'
  import { appColor } from '@/api/appColor'
  import { getAuth } from '@/api/login'
  export default {
    components: { GetUserInfo },
    data() {
      return {
        getImTokenData: '',
        listData: [],
        noneData: false,
        customerInfo: {},
        inMessage: false,
        getImUnreadSellerData: null,
        isGetUserInfo: false,
        getAppInfo: {}
      }
    },
    watch: {
      getInMessage(val) {
        if (val === '1') {
          this.getMemberInfoEls()
        }
      }
    },
    onLoad() {
      // 初始化data
      Object.assign(this.$data, this.$options.data())
      this.getAppEls()
      this.getAuth()
    },
    onShow() {
      if (!this.getCustomerId) {
        this.$pt.setStorageSync('messageListIn', true)
        this.isGetUserInfo = false
        setTimeout(() => {
          this.isGetUserInfo = true
        }, 100)
        return
      }
      setInMessage('0')
      this.getMemberInfoEls()
    },
    methods: {
      getAuth() {
        this.$pt.login({
          success(res) {
            if (res.code) {
              getAuth(res.code).then((response) => {
                setToken(response.data.token)
              }).catch(() => {
              })
            }
          }
        })
      },
      getAppEls() {
        getAppInfo().then((response) => {
          if (response.isError) return
          let getAppInfo = response.data
          this.getAppInfo = appColor(getAppInfo)
          this.getAppInfo.appVersion = process.env.VERSION
        }).catch(() => {
        })
      },
      // 游客点击授权按钮 获取用户基本信息
      showPage() {
        this.isGetUserInfo = false
      },
      getMemberInfoEls() {
        getMemberInfo(this.getCustomerId).then((response) => {
          if (response.isError) return
          this.customerInfo = response.data
          this.imGetToken()
        })
      },
      imGetToken() {
        imGetToken({
          userId: this.getCustomerId,
          name: this.customerInfo.nickname,
          portraitUri: this.customerInfo.avatar
        }).then((response) => {
          this.getImTokenData = response.token
          setImToken(response.token)
          this.imConnect()
        }).catch((res) => {
        })
      },
      imConnect() {
        const im = imInit()
        im.connect({ token: this.getImTokenData }).then(user => {
          this.initEls()
          console.log('detail 链接成功, 链接用户 id 为: ', user.id)
        }).catch(error => {
          if (error.code !== 34001) {
            console.log('detail 链接失败: ', error.code, error.msg)
            return
          }
          this.initEls()
          console.log('detail 链接失败: ', error.code, error.msg)
        })
      },
      onClose(value, event) {
      // 滑动单元格关闭事件
        const { position, instance } = event.mp.detail
        switch (position) {
        // 点击中间部分触发的事件
          case 'cell':
            console.log(111)
            instance.close()
            break
          case 'right':
            console.log(222)
            // 点击滑块右边触发的事件 (删除)
            this.remove(value.targetId)
            instance.close()
            break
        }
      },
      remove(id) {
        const im = imInit()
        const RongIMLib = RongIMLibInit()
        const conversation = im.Conversation.get({
          targetId: id,
          type: RongIMLib.CONVERSATION_TYPE.PRIVATE
        })
        const that = this
        this.$pt.showModal({
          content: '是否确认删除此消息？',
          success(res) {
            if (res.confirm) {
              conversation.destory().then((response) => {
                that.$utils.showToast({ title: '删除会话成功' })
                that.initEls()
              }).catch(err => {
                console.log(err)
              })
            } else if (res.cancel) {
              console.log('用户取消')
            }
          }
        })
      },
      initEls() {
        this.noneData = false
        const im = imInit()
        let that = this
        im.Conversation.getTotalUnreadCount().then(function(totalUnreadCount) {
          that.getImUnreadSellerData = totalUnreadCount
          that.$pt.setNavigationBarTitle({
            title: that.getImUnreadSellerData ? '消息(' + that.getImUnreadSellerData + ')' : '消息'
          })
        })
        im.Conversation.getList().then(list => {
          if (list.length) {
            that.listData = list
            that.listData.forEach(item => {
              if (item.latestMessage && item.latestMessage.content && item.latestMessage.messageType === 'RC:TxtMsg' && item.latestMessage.content.order) {
                item.latestMessage.content.content = that.$utils.getStrByLength(item.latestMessage.content.content, 20)
              }
              if (item.latestMessage && item.latestMessage.sentTime) {
                item.latestMessage.sentTime = that.$utils.formatMsgTime(item.latestMessage.sentTime)
              }
            })
            console.log('历史消息', that.listData)
          } else {
            that.noneData = true
          }
        }).catch(error => {
          that.$utils.showToast({ title: '获取会话列表失败' })
          // console.log('Token: ', this.getImToken)
          console.log(error)
          // this.$utils.showToast({
          //   title: error + ' ',
          //   duration: 500000
          // })
          console.log('获取会话列表失败: ', error)
        })
      },
      statusClick() {
        console.log('statusClick')
      }
    }
  }
</script>

<style lang="less" scoped>
  .container{
    background: #fff;
    color: #333333;
    min-height: calc(100vh);
    overflow: hidden;
    .content-s{
      height: 17px;
      line-height: 1.3;
      overflow:hidden;
      text-overflow:ellipsis;
      display:-webkit-box;
      -webkit-line-clamp:1;
      -webkit-box-orient:vertical;
      word-break:break-word;
    }
    .search-bar {
      padding: 4px 0px 10px 8px;
      width: 100%;
      box-sizing: border-box;
      background: white;
      position: fixed;
      left: 0;
      z-index: 1;
      .search {
        display: flex;
        justify-content: left;
        align-items: center;
        border-radius: 25px;
        height: 30px;
        color: #aeaeae;
        background-color: #f4f4f4;
      }
      .change-user{
        background: #fff4a3;
        border-top-left-radius: 20px;
        border-bottom-left-radius: 20px;
        height: 24px;
        line-height: 23px;
      }
    }
    .list{
      li{
        border-bottom: #eeeeee 1px solid;
        .font-bar-line{
          // height: 17px;
          // line-height: 1.3;
          // overflow:hidden;
          // text-overflow:ellipsis;
          // display:-webkit-box;
          // -webkit-line-clamp:1;
          // -webkit-box-orient:vertical;
          // word-break:break-word;
        }
        .avatar-img{
          border-radius: 100px;
          width: 48px;
          height: 48px;
        }
        h2{
          font-weight: normal;
        }
        .list-r{
          span{
            display: block;
            text-align: center;
            max-width: 68px;
            height: 17px;
            line-height: 1.3;
            overflow:hidden;
            text-overflow:ellipsis;
            display:-webkit-box;
            -webkit-line-clamp:1;
            -webkit-box-orient:vertical;
            word-break:break-word;
          }
          i{
            float: right;
          }
        }
        .van-infos {
          display: inline-block;
          color: #fff;
          font-size: 12px;
          font-weight: 500;
          font-family: PingFang SC, Helvetica Neue, Arial, sans-serif;
          text-align: center;
          box-sizing: border-box;
          padding: 0 3px;
          min-width: 16px;
          line-height: 14px;
          border: 1px solid #fff;
          border-radius: 16px;
          background-color: #ff1d1d;
          -webkit-transform: translateX(0) !important;
          transform: translateX(0) !important;
          -webkit-transform-origin: 100%;
          transform-origin: 100%;
        }
        /deep/ .van-swipe-cell__right {
          background: #ff4a4a;
          height: 100%;
          top: 0;
          color: white;
          width: 100%;
          padding-left: 13px;
          display: flex;
          align-items: center;
        }
      }
    }
  }
</style>
